import requests
import json
import time
import redis
from util.UTILS import *
from datetime import datetime
import asyncio
from notice.util.phone_notice import *
import aiohttp

def getLogger(name):
    log_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')  # 使用下划线和横杠替代非法字符
    filename = os.path.join(os.path.dirname(__file__), f"{name}-{log_time}.log")

    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    file_handler = logging.FileHandler(filename, mode='w')
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)

    logger.addHandler(file_handler)

    return logger

# Redis连接配置
redis_client = redis.Redis(
    host='47.245.62.138',
    port=6397,
    db=0,
    password='mq0MgbBEZzvFUpEy',  # 设置Redis密码
    decode_responses=True  # 自动将响应解码为字符串
)

phone_notice_clinet = PhoneNotice.create_client()

logger = getLogger('zz')



url = 'https://kyb-api.520iy.com/public/sendWxMsg'

async def task(n):
    print(f"Task {n} started")
    await asyncio.sleep(1)
    print(f"Task {n} completed")
    return n

# user_amount  用户总份额 per_portion_val 每份价值
async def send_msg(openid,one,two,diff,content,phone):

    print("start:" + openid)
    paras = {}
    paras['openid'] = openid
    msg = {}
    paras['msg'] = msg
    paras['url'] = 'https://app.blocksec.com/explorer/tx/bsc/' + content
    msg['type'] = 'income_msg'
    msg['one'] = one
    msg['two'] = two
    msg['diff'] = diff

    msg['time'] = ''

    print(paras)
    async with aiohttp.ClientSession() as session:
        async with session.post(url, json=paras) as response:
            print(await response.text())
    await PhoneNotice.call_async([phone])
    print("complete:" + openid)

def test_redis_connection():
    """
    测试Redis连接
    """
    try:
        redis_client.ping()
        logger.info("Redis连接成功！")
        return True
    except Exception as e:
        logger.info(f"Redis连接失败: {e}")
        return False

def write_to_redis(key, data):
    """
    将数据写入Redis
    :param key: Redis键名
    :param data: 要存储的数据
    :return: bool
    """
    try:
        # 将数据转换为JSON字符串
        # json_data = json.dumps(data, ensure_ascii=False)
        # 使用set方法存储数据，不设置过期时间
        redis_client.set(key, data)
        # print(f"数据已成功写入Redis，键名: {key}")
        logger.info(f"数据内容: {data}")
        return True
    except Exception as e:
        logger.info(f"写入Redis时出错: {e}")
        return False

def read_from_redis(key):
    """
    从Redis读取数据
    :param key: Redis键名
    :return: 数据或None
    """
    try:
        # 获取数据
        data = redis_client.get(key)
        if data:
            logger.info(f"成功从Redis读取数据，键名: {key}")
            logger.info(f"数据内容: {data}")
            return data
        logger.info(f"Redis中没有找到键名为 {key} 的数据")
        return None
    except Exception as e:
        logger.info(f"从Redis读取数据时出错: {e}")
        return None

def get_transactions():
    url = "https://api.bscscan.com/api"
    params = {
        "module": "account",
        "action": "txlist",
        "address": "0xe0c7897d48847b6916094bf5cd8216449ea8fb86",
        "startblock": "0",
        "endblock": "99999999",
        "page": "1",
        "offset": "20",
        "sort": "desc",
        "apikey": "76XXC42YD6PTHQ1857STYNS4N4RR4TXKYD"
    }
    
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()
    except requests.exceptions.RequestException as e:
        logger.info(f"请求出错: {e}")
        return None

ido_hash_key = 'ido_cach_key'
async def main():
    logger.info("开始监控交易...")
    while True:
        try:

            result = get_transactions()
            if result:
                ido_cach_hash = read_from_redis(ido_hash_key)
                for row in result['result']:
                    if row['methodId'] == '0xfd5c9779':
                        hash = row['hash']
                        # print(hash)
                        if hash == ido_cach_hash:
                            logger.info("hash {}  已经发过通知了 ".format(hash))
                        else:
                            if write_to_redis(ido_hash_key,hash):
                                asyncio.gather(send_msg("ocAr152-22tVKGt2Fp-E9GZ06Oos","币安TGE活动通知",hash,'',hash,'18674874300'),
                                send_msg('ocAr157l0xBsK2-WVZKjuPn0rzfs',"币安TGE活动通知",hash,'',hash,'17375810339'),
                                send_msg('ocAr1534Q295U02-OvVaQDnsIsNY',"币安TGE活动通知",hash,'',hash,''),
                                send_msg('ocAr158wqTDshbf8GZQXXQmW3ljU',"币安TGE活动通知",hash,'',hash,'18857708346'),
                                send_msg('ocAr1570xVR_cmVq8-_g2GlC-jhQ',"币安TGE活动通知",hash,'',hash,'15794798580')
                                               )





                        break
                # print("\n当前交易数据:")
                # json_result = json.dumps(result, indent=2, ensure_ascii=False)
                # print(json_result)


                # 生成Redis键名（使用时间戳）
                # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
                # redis_key = f"bsc_transactions_{current_time}"
                #
                # # 写入Redis
                # write_to_redis(redis_key, result)
                #
                # # 读取Redis数据（示例）
                # redis_data = read_from_redis(redis_key)
                # if redis_data:
                #     print("\n从Redis读取的数据:")
                #     print(json.dumps(redis_data, indent=2, ensure_ascii=False))

            time.sleep(10)  # 等待10秒
        except Exception as e:
            logger.info(e)


async  def so():
    tasks = [task(i) for i in range(10)]
    results = await asyncio.gather(*tasks)
    print(f"Total results: {len(results)}")
async def bo():

    await asyncio.gather(
        send_msg('ocAr152-22tVKGt2Fp-E9GZ06Oos', "币安TGE活动通知", 'testset', '', 'testset','18674874300'),
        send_msg('ocAr152mwMGbfHd_tZFujQ3vhAfA', "币安TGE活动通知", 'testset', '', 'testset','17375810339')
    )


if __name__ == "__main__":

    #main()
    print("ss")
    #send_msg('ocAr1570xVR_cmVq8-_g2GlC-jhQ', "币安TGE活动通知", 'testset', '', 'testset')
    asyncio.run(bo())
    print('hh')
    # asyncio.run(test())
    # 首先测试Redis连接
    # if test_redis_connection():
    #     # 写入测试数据
    #     write_to_redis('', '11')
    #     # 立即读取测试数据
    #     read_from_redis('testkey')
    # else:
    #     print("Redis连接失败，请检查连接配置")